package tableRelations.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtils {
	private static SessionFactory sf=null;
	static {
        StandardServiceRegistry serviceRegistry =  new StandardServiceRegistryBuilder().configure().build();
        Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
        sf = metadata.getSessionFactoryBuilder().build();
	}
	
	public static SessionFactory getSessionFactory() {
		return sf;
	}
	
	private static final ThreadLocal<Session> LOCAL=new ThreadLocal<Session>();
	
	public static Session getSession() {
		Session session=LOCAL.get();
		if(session==null) {
			session=sf.openSession();
			LOCAL.set(session);
		}
		return session;
	}
	
	public static void closeSession() {
		Session session=LOCAL.get();
		if(session!=null) {
			session.close();
			LOCAL.set(null);
		}
	}
	
	public static void shutdown() {
		getSessionFactory().close();
	}
}
